package com.nursebetty.server.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.nursebetty.server.common.UserProfile;
import com.nursebetty.server.dao.UserDao;

public class UserDaoImpl implements UserDao{
	private JdbcTemplate jdbcTemplate;
	
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	
	@Override
	public UserProfile SignUp(String userName, String password) {
		String sql="insert into USR(USR_NAME,PASSWORD) values (?,?) ";
		jdbcTemplate.update(sql, new Object[] {userName, password });
		return ValidateLogin(userName, password);
	}


	@Override
	public UserProfile ValidateLogin(String userName, String password) {
		String sql = "select * from USR where USR_NAME='" + userName + "' AND PASSWORD='" + password +"'";
		List<UserProfile> result = jdbcTemplate.query(sql, new UserMapper());
		if (result != null && result.size() >0){
			return result.get(0);
		}
		return null;
	}

	private class UserMapper implements RowMapper {

		public UserProfile mapRow(ResultSet rs, int rowNum) throws SQLException {
			UserProfile usr = new UserProfile();
			usr.setId(rs.getInt("USR_ID"));
			usr.setUsername(rs.getString("USR_NAME"));
			return usr;
		}
	}
	
}
